import * as Cesium from "cesium";

// let polylineFlowShader = ;
class PolylineFlowMaterialProperty {
  static materialType = "PolylineFlow";
  // 注册材质
  static register() {
    if (
      Cesium.Material._materialCache.getMaterial(
        PolylineFlowMaterialProperty.materialType
      )
    ) {
      return; // 已注册则跳过
    }
    Cesium.Material._materialCache.addMaterial(
      PolylineFlowMaterialProperty.materialType,
      {
        fabric: {
          type: PolylineFlowMaterialProperty.materialType,
          uniforms: {
            color: Cesium.Color.ORANGE,
            glowPower: 0.25,
            taperPower: 1.0,
          },
          source: `
czm_material czm_getMaterial(czm_materialInput materialInput)
      {
        czm_material material = czm_getDefaultMaterial(materialInput);
        // vec3 baseColor = rgb(1.0, 1.0, 0.0);
        // material.diffuse = baseColor;
        return material;
      }
      `,
        },
        translucent: () => true,
      }
    );
  }
  constructor(options) {
    this._definitionChanged = new Cesium.Event();
    this._color = undefined;
    this._glowPower = undefined;
    this._taperPower = undefined;
    this.color = options.color ?? Cesium.Color.ORANGERED;
    this.glowPower = options.glowPower ?? 0.25;
    this.taperPower = options.taperPower ?? 1.0;
  }
  // ✅ 是否常量
  get isConstant() {
    return (
      Cesium.Property.isConstant(this._color) &&
      Cesium.Property.isConstant(this._glowPower) &&
      Cesium.Property.isConstant(this._taperPower)
    );
  }
  // ✅ 属性变化事件
  get definitionChanged() {
    return this._definitionChanged;
  }

  // ✅ 材质类型名
  getType() {
    return PolylineFlowMaterialProperty.materialType;
  }
  // ✅ 获取当前时间对应的uniform值
  getValue(time, result) {
    if (!Cesium.defined(result)) {
      result = {};
    }
    result.color = Cesium.Property.getValueOrClonedDefault(
      this._color,
      time,
      Cesium.Color.ORANGE,
      result.color
    );
    result.glowPower = Cesium.Property.getValueOrDefault(
      this._glowPower,
      time,
      0.25
    );
    result.taperPower = Cesium.Property.getValueOrDefault(
      this._taperPower,
      time,
      1.0
    );
    return result;
  }
  // ✅ 判断是否相等，作用：判断两个 Property 是否等价 就是用来完成这个“是否变化”的判断。
  equals(other) {
    return (
      this === other ||
      (other instanceof PolylineFlowMaterialProperty &&
        Cesium.Property.equals(this._color, other._color) &&
        Cesium.Property.equals(this._glowPower, other._glowPower) &&
        Cesium.Property.equals(this._taperPower, other._taperPower))
    );
  }
}

Object.defineProperties(PolylineFlowMaterialProperty.prototype, {
  color: Cesium.createPropertyDescriptor("color"),
  glowPower: Cesium.createPropertyDescriptor("glowPower"),
  taperPower: Cesium.createPropertyDescriptor("taperPower"),
});

export default PolylineFlowMaterialProperty;
